﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Web;
using System.Web.Mvc;

using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using BTFEED.Models;
using HtmlAgilityPack;

namespace BTFEED.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public string GetWebContent(string strLink)
        {
            string strContent = "";
            try
            {
                WebRequest objWebRequest = WebRequest.Create(strLink);
                objWebRequest.Credentials = CredentialCache.DefaultCredentials;
                WebResponse objWebResponse = objWebRequest.GetResponse();
                Stream receiveStream = objWebResponse.GetResponseStream();
                StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8);
                strContent = readStream.ReadToEnd();
                objWebResponse.Close();
                readStream.Close();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return strContent;
        }


        public JsonResult GetFeed()
        {
            if (Request.IsAjaxRequest())
            {
                /*return Json(LayTieuDe(
                     GetWebContent("http://vnexpress.net/gl/xa-hoi/2012/08/phu-nu-chet-loa-the-trong-khach-san/"))
                      + "<br/><br/>"
                      +
                      LayMoTa(GetWebContent("http://vnexpress.net/gl/xa-hoi/2012/08/phu-nu-chet-loa-the-trong-khach-san/"))
                      + "<br/><br/>"
                      +
                      LayNoiDung(
                          GetWebContent("http://vnexpress.net/gl/xa-hoi/2012/08/phu-nu-chet-loa-the-trong-khach-san/"))
                      + "",JsonRequestBehavior.AllowGet);
                */

              //  return Json(LayFeed(GetWebContent("http://www.fit.hcmus.edu.vn/vn/Default.aspx?tabid=53")), JsonRequestBehavior.AllowGet);
            }
            return Json("eafaef");
        }



        private List<FeedModel> feedModels = new List<FeedModel>();
       /* public string layNgay(string Content)
        {
            string pattern = "<div class=\"day_month\">[^<]+";
            Regex Title = new Regex(pattern);
            MatchCollection mat = Title.Matches(Content);
            string a = "";
            foreach (Match m in mat)
            {
                date.Add(m.Value);
                a += m.Value + " ";
            }
            return a;

        }

        public string layTieuDe(string Content)
        {
            Content = Content.Replace("\n", "");
            // string pattern = "<a title=\".*? href=\"(?<link>.*?)\">(?<text>.*?)</a>";
            string pattern = "<div class=\"post_title\">.*?href=\"(?<link>.*?)\">(?<text>.*?)</a>";
            Regex Title = new Regex(pattern);

            MatchCollection mat = Title.Matches(Content);
            string a = "";
            foreach (Match m in mat)
            {
                date.Add(m.Value);
                //a += m.Value + " ";
                a += m.Groups["link"].Value + "\t|\t" + m.Groups["text"].Value + "\n\n";
            }
            return a;

        }


        public string LayMoTa(string Content)
        {
            string pattern = "<H2 class=Lead>[^<]+";
            Regex Title = new Regex(pattern);
            Match m = Title.Match(Content);
            if (m.Success)
                return m.Value.Substring(15, m.Value.Length - 15);
            return "";
        }


        public string LayNoiDung(string Content)
        {
            string pattern = "<P class=Normal>[^~]+";
            Regex Title = new Regex(pattern);
            Match m = Title.Match(Content);
            if (m.Success)
                return m.Value.Substring(16, m.Value.Length - 16).Replace("/Files", "http://vnexpress.net/Files").Replace("/gl", "http://vnexpress.net/gl");
            return "";
        }*/
        public void LayFeed(string Content)
        {
            var webSite = new HtmlWeb();     //tạo một object chứa trang web

            var doc = webSite.Load("http://www.fit.hcmus.edu.vn/vn/Default.aspx?tabid=53");

            var title = doc.DocumentNode.SelectNodes("//div[@class='post_title']");
            var date = doc.DocumentNode.SelectNodes("//div[@class='day_month']");

            if (title != null && date !=null)
            {
                for (int i = 0 ; i< title.Count ;i++)
                {
                    var temp = title[i].FirstChild.NextSibling;
                    IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
                    DateTime ngay = DateTime.Parse(date[i].InnerText, culture);
                    feedModels.Add(new FeedModel
                        {
                          
                            Date = ngay,
                            Title = title[i].InnerText.Replace("&nbsp;",""),
                            Url  = "http://www.fit.hcmus.edu.vn/vn/"+temp.Attributes["href"].Value
                             
                        });
                }
            }
           
           
        }

        public RssResult Feed()
        {
            LayFeed(null);
            var feed = new SyndicationFeed("Khoa CNTT DHKHTN Feeds",
                " Khoa CNTT Tin tức Feed", new Uri("http://www.fit.hcmus.edu.vn/vn/"));
 
            var items = new List<SyndicationItem>();
 
            for (var i = 0; i < feedModels.Count; i++)
            {
                var item =
                    new SyndicationItem("["+feedModels[i].Date.Date.ToString("dd/MM/yyyy")+"]" + feedModels[i].Title,
                    "",
                    new Uri(feedModels[i].Url),
                    i.ToString(),
                   feedModels[i].Date);
                items.Add(item);
 
            }
            feed.Items = items;
 
            return new RssResult(feed);
        }
    
        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}
